import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

interface StateProps {
  // 搜索数据列表,数据库返回的
  data: ContentType[]
  setData: (data: ContentType[]) => void
  // 搜索关键字,用户输入的
  search: string
  setSearch: (search: string) => void
  // 错误信息
  error: string
  setError: (error: string) => void
  // 当前选中数据的id
  id: number
  setId: (id: number) => void

  // 编辑分类id
  editCategoryId: number
  setEditCategoryId: (id: number) => void

  // 配置项
  config: ConfigContentType
  setConfig: (config: ConfigContentType) => void
}

export const useStore = create(
  persist<StateProps>(
    (set) => ({
      data: [],
      setData: (data) => set({ data }),
      search: '',
      setSearch: (search) => set({ search }),
      error: '',
      setError: (error) => set({ error }),
      id: 0,
      setId: (id) => set({ id }),
      editCategoryId: 0,
      setEditCategoryId: (editCategoryId) => set({ editCategoryId }),
      config: { shortcut: 'Control+shift+;', databaseDirectory: '' },
      setConfig: (config) => set({ config })
    }),
    {
      // 持久化存储
      name: 'snippet-storage',
      // 存储方式，这里用的是本地json文件的方式
      storage: createJSONStorage(() => localStorage)
    }
  )
)
